import store from '@/store'
import router from '@/router'
import axios from 'axios' // 引入axios
import { Message } from 'element-ui'// 引入element的Message插件

import { BASEURL } from '@/control'// 服务器地址
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: BASEURL + '/purchase',
  timeout: 10 * 1000
})
service.interceptors.request.use(config => { // 请求拦截器
  config.headers = {
    'Content-Type': 'application/json'
  }
  const token = getToken()
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, error => {
  Promise.reject(error)
})
service.interceptors.response.use(response => {
  // console.log('接收到response(全部):', response)
  if (response.data.code) {
    if (response.data.code === '200') {
      return response.data
    } else {
      Message.error(response.data.msg)
      return Promise.reject(false)
    }
  } else {
    if (response.config.url.indexOf('downexcel')) {
      return response
    }
    Message.error('error')
    return Promise.reject(false)
  }
}, error => {
  // console.log('接收到error(全部):', error)
  // console.log('接收到error.response:', error.response)
  if (error.response.status === 401) {
    if (document.getElementsByClassName('el-message').length === 0) {
      let tip = 'Sila log masuk sekali!'
      if (error.response.data.msg) {
        if (error.response.data.msg.length > 0) {
          tip = error.response.data.msg
        }
      }
      Message.error(tip)
    }
    store.dispatch('user/logout').then(res => {
      router.push({ path: '/login' })
    }).catch(err => {
      console.log(err)
    })
  } else {
    Message.error(error)
  }
  return Promise.resolve(error.response)
})
// 4.导入文件
export default service
